package com.cqgc.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    // 死信交换机
    public static final String ORDER_DEAD_LETTER_EXCHANGE = "order_dead_letter_exchange";
    // 正常队列
    public static final String ORDER_QUEUE_NAME = "order_queue";
    // 死信队列路由键
    public static final String ORDER_DEAD_LETTER_ROUTING_KEY = "order.deadletter";
    // 死信队列名称
    public static final String ORDER_DEAD_LETTER_QUEUE_NAME = "order_dead_letter_queue";

    // 消息存活时间，单位毫秒
    public static final int ORDER_TTL = 300000; // 6分钟

    /**
     * 创建死信交换机
     */
    @Bean
    DirectExchange orderDeadLetterExchange() {
        return new DirectExchange(ORDER_DEAD_LETTER_EXCHANGE);
    }

    /**
     * 创建正常队列，并设置TTL和死信交换机及路由键
     */
    @Bean
    Queue orderQueue() {
        return QueueBuilder.durable(ORDER_QUEUE_NAME)
                .withArgument("x-message-ttl", ORDER_TTL) // 设置消息TTL
                .withArgument("x-dead-letter-exchange", ORDER_DEAD_LETTER_EXCHANGE) // 设置死信交换机
                .withArgument("x-dead-letter-routing-key", ORDER_DEAD_LETTER_ROUTING_KEY) // 设置死信路由键
                .build();
    }

    /**
     * 创建死信队列
     */
    @Bean
    Queue orderDeadLetterQueue() {
        return new Queue(ORDER_DEAD_LETTER_QUEUE_NAME, true); // 死信队列为持久化队列
    }

    /**
     * 绑定死信队列到死信交换机
     */
    @Bean
    Binding deadLetterBinding(DirectExchange orderDeadLetterExchange, Queue orderDeadLetterQueue) {
        return BindingBuilder.bind(orderDeadLetterQueue).to(orderDeadLetterExchange).with(ORDER_DEAD_LETTER_ROUTING_KEY);
    }

    /**
     * 配置消息转换器
     */
    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
